package com.larry.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @ProjectName JUC
 * @Author larry
 * @Date 15:16 2021/7/16
 * @Description TODO
 **/

class BankAccount {
    String bankName = "icbc";
    //以一种线程安全的方式操作非线程安全对象内的某些字段
    //更新的对象属性必须使用public volatile修饰符
    public volatile int money = 0;
    //因为对象的属性修改类型原子类都是抽象类，所以每次使用都必须
    //使用静态方法newUpdater()创建一个更新器
    AtomicIntegerFieldUpdater fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class,"money");

    public void transfer(BankAccount bankAccount){
        fieldUpdater.incrementAndGet(bankAccount);
    }
}

public class AtomicIntegerFieldUpdaterDemo {

    public static void main(String[] args) {
        BankAccount bankAccount = new BankAccount();

        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                bankAccount.transfer(bankAccount);
            },String.valueOf(i)).start();
        }
        try { TimeUnit.SECONDS.sleep(1); }catch (InterruptedException e){ e.printStackTrace(); }

        System.out.println(Thread.currentThread().getName() + " --- " + bankAccount.money);

    }
}
